package scope

import (
	"strings"

	"gorm.io/gorm"
)

func WithSelects(selects ...string) IScope {
	rules := make(SelectRules, len(selects))
	for i, s := range selects {
		rules[i] = parseSelectRule(s)
	}
	return rules
}

type SelectRules []SelectRule

func parseSelectRule(s string) SelectRule {
	c, a := "", ""
	mixed := strings.Contains(s, " AS ") || strings.Contains(s, " as ") || strings.Contains(s, " As ")
	if mixed {
		ss := strings.Split(s, " AS ")
		c = ss[0]
		a = ss[1]
	} else {
		c = s
	}
	return SelectRule{
		Column: c,
		Alias:  a,
	}
}

type SelectRule struct {
	Column string
	Alias  string
}

func (s SelectRules) MakeScope() Scope {
	return func(db *gorm.DB) *gorm.DB {
		if len(s) > 0 {
			for _, r := range s {
				db = r.handleOrm(db)
			}
		}
		return db
	}
}

func (s SelectRule) MakeScope() Scope {
	return s.handleOrm
}

func (s SelectRule) handleOrm(db *gorm.DB) *gorm.DB {
	if s.Alias != "" {
		return db.Select(s.Column + " AS " + s.Alias)
	}
	return db.Select(s.Column)
}
